<template>
	<view class="content">
		<view class="header" :style="{background:$store.state.bgPrimaryColor}">
			<view class="view" v-for="(item,index) in columns" :key="index" @click="getActive(index)">
				<text>{{item.label}}</text>
				<u--image :showLoading="true" src="../../static/login/sanjiao.png" width="24rpx" height="24rpx"
					radius="0"></u--image>
			</view>
		</view>
		<view class="Box" v-if="lists.length > 0">
			<view v-for="(item,index) in lists" :key="index">
				<view class="BoxView">
					<view class="BoxOne">
						<view style="display: flex;align-items: center;">
							<u--image :showLoading="true" :src="item.teacher &&item.teacher.avatar || default_img"
								width="94rpx" height="94rpx" radius="0" shape="circle"></u--image>
							<view class="BoxContent">
								<view class="BoxTop marginBottom">
									<text class="title" style="">{{item.teacher && item.teacher.name || ''}}</text>
									<text
										style="color:#888888;margin-left:15rpx;white-space: nowrap;">{{item.teacher && item.teacher.country.name}}教师</text>
								</view>
								<view class="BoxTop">
									<text class="Newtitle"
										style="white-space: nowrap;">{{item.teacher && item.teacher.speciality}}</text>
								</view>
							</view>
						</view>
						<button class="cancel" @click="cancel(item)" v-if="item.status_text == '预约中'"
							:style="{'background':$store.state.buttonColor,'white-space':'nowrap'}">预约取消</button>
						<button class="cancel"
							@click="linkUrl(`/pages/Teacher/Publish_comments?teacher_id=${item.teacher_id}&shop_id=${item.shop_id}&order_id=${item.order_id}&reservation_id=${item.id}`)"
							v-if="item.status_text == '已结束' && item.comment_status== 1"
							:style="{'background':$store.state.buttonColor,'white-space':'nowrap'}">待评价</button>
					</view>
					<view class="BoxBottom">
						<text class="title">{{item.name}}</text>
						<view class="TimeFlex">
							<text class="TimeTitle">距离课程开始</text>
							<uni-countdown color="#F1330D" background-color="#FFB5B5" :day="item.time.days"
								:hour="item.time.hours" :minute="item.time.minutes" :second="item.time.seconds"
								v-if="item.status_text == '预约中'" />
							<!-- <u-count-down :time="item.time * 1000" format="HH:mm:ss" autoStart millisecond
								@change="onChange">
								<view class="time">
									<view class="time__custom">
										<text
											class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
									</view>
									<text class="Timetext">小时</text>
									<view class="time__custom">
										<text class="time__custom__item">{{ timeData.minutes }}</text>
									</view>
									<text class="Timetext">分</text>
									<view class="time__custom">
										<text class="time__custom__item">{{ timeData.seconds }}</text>
									</view>
									<text class="Timetext">秒</text>
								</view>
							</u-count-down> -->
						</view>
						<view class="Boxinfo">
							<view class="u-Flex">
								<u--image :showLoading="true" src="../../static/Home/rqi.png" width="26rpx"
									height="26rpx" radius="0"></u--image>
								<text>{{item.date}}</text>
								<text>{{getday(item.date)}}</text>
							</view>
							<view class="u-Flex">
								<u--image :showLoading="true" src="../../static/Home/shijian.png" width="28rpx"
									height="28rpx" radius="0"></u--image>
								<text>{{item.start_time}}-{{item.end_time}}</text>
							</view>
							<view class="u-Flex">
								<u--image :showLoading="true" src="../../static/Home/cishu.png" width="24rpx"
									height="24rpx" radius="0"></u--image>
								<text v-if="item.vip">{{item.usage}}次/{{item.total}}次</text>
							</view>
						</view>
						<u-line-progress :percentage="(item.usage/(item.total) *100).toFixed(2)" height="15"
							:activeColor="$store.state.primaryColor" v-if="item.vip"></u-line-progress>
					</view>
				</view>
				<view class="checkTx" @click="huiyi(item.teacher_id)" style="margin-bottom:0rpx;">
					<text class="checkTx_title">老师腾讯会议号</text>
					<view class="checkTx_view">
						<text class="checkTx_Text">查看会议号与密码</text>
						<u--image :showLoading="true" src="../../static/more.png" width="34rpx" height="34rpx"
							radius="0"></u--image>
					</view>
				</view>
				<view class="checkTx" v-if="item.is_teacher_comment == 1"
					@click="linkUrl(`/pages/Mine/MyCourseReport?id=${item.id}`)" style="margin-top:0rpx;">
					<text class="checkTx_title">老师评价</text>
					<view class="checkTx_view">
						<text class="checkTx_Text">查看本节课报告</text>
						<u--image :showLoading="true" src="../../static/more.png" width="34rpx" height="34rpx"
							radius="0"></u--image>
					</view>
				</view>
			</view>
		</view>
		<view class="" v-if="arr == 2 && lists.length != 0"
			style="font-weight: 600;text-align: center;margin-top: 30rpx;"> 加载完毕... </view>
		<view class="empty" v-if="lists.length == 0">
			<image src="../../static/null.png" mode="widthFix"></image>
			<text>暂时没有课程</text>
		</view>
		<u-popup :show="isShow" @close="isShow = false" @open="isShow = true" mode="center" round="20">
			<view class="NewpopupBody">
				<text class="title">确定取消预约吗？</text>
				<view class="but_flex">
					<button class="leftButton" @click="isShow = false"
						:style="{'background':$store.state.cancelColor}">取消</button>
					<button class="rightButton" @click="clearReservation()"
						:style="{'background':$store.state.buttonColor}">确定</button>
				</view>
			</view>
		</u-popup>
		<u-picker :show="show" :columns="statusType" keyName="label" @cancel="show = false"
			@confirm="confirm"></u-picker>
		<u-datetime-picker :show="datetimeShow" v-model="value1" mode="year-month" @cancel="datetimeShow = false"
			@confirm="confirmDatetime"></u-datetime-picker>
	</view>
</template>
<script>
	import {
		getUserCourse,
		clearReservation
	} from '../../api/Course.js';
	import uniCountdown from '@/uni_modules/uni-countdown/uni-countdown/components/uni-countdown/uni-countdown.vue';
	export default {
		components: {
			uniCountdown
		},
		data() {
			return {
				default_img: 'https://yue-ke.oss-cn-guangzhou.aliyuncs.com/public/uploads/20240707/d8904c3496785357be2d737b37fb1641.png',
				show: false,
				id: 0,
				datetimeShow: false,
				value1: Number(new Date()),
				isShow: false,
				timeData: {},
				inx: 0,
				arr: 0,
				columns: [{
					label: '预约中',
					id: 804
				}, {
					label: '时间',
					id: 804
				}],
				statusType: [
					[{
						label: '全部',
						id: 0
					}, {
						label: '预约中',
						id: 1
					}, {
						label: '已取消',
						id: -1
					}, {
						label: '已结束',
						id: 3
					}]
				],
				req: {
					shop_id: 0,
					limit: 999,
					page: 1,
					date: '',
					type: '',
					reservation_type: 1, //预约状态，0=取消,1=预约中，2上课中
					reservation_Name: '',
					month_date: '', //年月份，2024-7月份
				},
				lists: [],
				time: 0,
				hour: '',
				minute: '',
				miao: '',
				day: '',
				hasMore: true,
				isClicked: false
			}
		},
		onReachBottom() {
			if (this.hasMore) {
				this.req.page += 1;
				this.getUserCourse(1);
			}
		},
		methods: {
			getday(time) {
				const targetDate = new Date(time);
				const dayOfWeek = targetDate.getDay();
				const daysOfWeekChinese = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
				const currentDayOfWeekChinese = daysOfWeekChinese[dayOfWeek];
				return currentDayOfWeekChinese;
			},
			onUnload() {
				uni.navigateTo({
					url: 'pages/Tabbar/Mine/Mine'
				});
			},
			linkUrl(e) {
				uni.navigateTo({
					url: e
				});
			},
			getActive(index) {
				this.inx = index;
				if (index == 0) this.show = true;
				if (index == 1) this.datetimeShow = true;
				this.req.page = 1;
				this.getUserCourse();
			},
			timestampToYearMonth(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = date.getMonth() + 1; // 月份从0开始，需要加1
				return `${year}-${month < 10 ? '0' : ''}${month}`;
			},
			confirmDatetime(e) {
				this.req = {
					...this.req,
					...{
						month_date: this.timestampToYearMonth(e.value)
					}
				};
				this.columns[1].label = this.timestampToYearMonth(e.value);
				this.datetimeShow = false;
				this.getUserCourse();
			},
			confirm(e) {
				console.log(e)
				console.log(e.value[0])
				this.req = {
					...this.req,
					...{
						reservation_type: e.value[0].id,
						reservation_Name: e.value[0].label
					}
				};
				this.columns[0].label = e.value[0].label;
				this.show = false;
				this.lists = [];
				this.getUserCourse(0);
			},
			chengIn() {
				let date = new Date();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				this.day = date.getDate().toString().padStart(2, '0');
				this.hour = date.getHours().toString().padStart(2, '0');;
				this.minute = date.getMinutes().toString().padStart(2, '0');;
				this.miao = date.getSeconds().toString().padStart(2, '0');;
			},
			onLoad() {
				this.chengIn()
				this.req.shop_id = uni.getStorageSync('shop_id') || 1;
				this.getUserCourse();
				this.columns[0].label = '预约中';
			},
			onChange(e) {
				// /console.log(e)
				this.timeData = e
			},
			cancel(item) {
				this.isShow = true;
				this.id = item.id
			},
			huiyi(e) {
				uni.navigateTo({
					url: 'Appointment_number?teacher_id=' + e
				})
			},
			getSecondsDifference(targetTime) {
				// 将目标时间转换为Date对象
				const targetDate = new Date(targetTime);
				// 获取当前时间
				const currentDate = new Date();
				// 计算时间差（毫秒级）
				const difference = targetDate - currentDate;
				console.log(currentDate)
				console.log(targetDate)
				// 将时间差转换为秒
				const secondsDifference = Math.floor(difference / 1000);
				return secondsDifference > 0 ? secondsDifference : 0;
			},
			timeUntil(endTime) {
				let systemInfo = uni.getSystemInfoSync();
				let platform = systemInfo.platform;
				const now = new Date();
				if (platform === 'android') {
					var end = new Date(endTime);
				} else if (platform === 'ios') {
					var end = new Date(endTime.replaceAll("-", "/"));
				} else {
					var end = new Date(endTime);
				}
				const diff = end.getTime() - now.getTime(); // 时间差（毫秒）
				// 如果 endTime 已经过去，返回 0
				if (diff < 0) {
					return {
						days: 0,
						hours: 0,
						minutes: 0,
						seconds: 0
					};
				}
				// 计算差值的天、小时、分钟和秒
				let days = diff / (1000 * 60 * 60 * 24);
				days = Math.floor(days);
				let hours = (diff - (days * 1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
				hours = Math.floor(hours);
				let minutes = (diff - (days * 1000 * 60 * 60 * 24) - (hours * 1000 * 60 * 60)) / (1000 * 60);
				minutes = Math.floor(minutes);
				let seconds = (diff - (days * 1000 * 60 * 60 * 24) - (hours * 1000 * 60 * 60) - (minutes * 1000 * 60)) /
					1000;
				seconds = Math.floor(seconds);
				return {
					days,
					hours,
					minutes,
					seconds
				};
			},
			async getUserCourse(e = null) {
				let req = {
					...this.req,
					...{
						type: 0
					}
				};
				try {
					const res = await getUserCourse(req);
					if (res.data.data.length == 0) return false;
					res.data.data.forEach(item => {
						item.time = this.timeUntil(item.date + ' ' + item.start_time)
					});
					if (res.data.data.length < this.req.limit) {
						this.arr = 2
						this.hasMore = false;
					}
					if (e === 1) {
						this.lists = [...this.lists, ...res.data.data];
					} else {
						this.lists = [...res.data.data];
					}
				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			},
			async clearReservation() {
				try {
					if (this.isClicked) return;
					this.isClicked = true; // 设置按钮为点击状态
					let ids = this.id
					let shop_id = this.req.shop_id
					const res = await clearReservation({
						id: ids,
						shop_id: shop_id
					});
					this.isShow = false
					if (res.code == 1) {
						uni.showToast({
							title: '取消成功',
							icon: 'none',
							duration: 2000
						});
					}
					setTimeout(() => {
						// 操作完成后，重置按钮状态
						this.isClicked = false;
					}, 500);
					this.getUserCourse()
				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			}
		}
	}
</script>
<style>
	page {
		background-color: #f6f7f9;
	}
</style>
<style scoped lang="scss">
	button::after {
		border: none;
	}

	.content {
		padding-bottom: 50rpx;

		/deep/ .u-safe-bottom {
			display: none;
		}

		.empty {
			image {
				width: 100%;
			}

			text {
				display: block;
				text-align: center;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 36rpx;
				color: #333333;
			}
		}

		.NewpopupBody {
			width: 550rpx;
			height: auto;
			padding-top: 50rpx;
			padding-bottom: 50rpx;
			background-color: transparent;

			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 36rpx;
				color: #333333;
				display: block;
				text-align: center;
			}

			.content_text {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 24rpx;
				color: #999999;
				display: block;
				text-align: center;
				padding-top: 30rpx;
				padding-bottom: 30rpx;
			}

			.but_flex {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 50rpx;

				.leftButton {
					width: 40%;
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 32rpx;
					color: #333333;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50rpx;
					background-color: #efefef;
				}

				.rightButton {
					width: 40%;
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 32rpx;
					color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50rpx;
				}
			}
		}

		.header {
			width: auto;
			padding: 20rpx 20rpx 0rpx 30rpx;
			display: flex;
			align-items: center;

			.view {
				width: auto;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-right: 160rpx;
				padding-bottom: 20rpx;

				text {
					border-bottom: 3px solid transparent;
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 28rpx;
				}
			}

			/deep/ .u-image {
				margin-left: 15rpx;
			}
		}

		.Box {
			.BoxView {
				width: 85%;
				margin: 0px auto;
				background-color: #fff;
				border-radius: 20rpx;
				padding: 30rpx 30rpx 30rpx 30rpx;
				margin-top: 20rpx;

				.cancel {
					margin-left: 40rpx;
					color: #fff;
					font-weight: 500;
					background-color: #f6f7f9 !important;
				}
			}

			.BoxOne {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-bottom: 25rpx;
				border-bottom: 1px solid #F2F2F2;

				.marginBottom {
					margin-bottom: 10rpx;
				}

				.BoxTop {
					margin-left: 20rpx;
					display: flex;
					align-items: center;

					text {
						display: block;
						font-size: 24rpx;
					}

					.title {
						font-family: PingFangSC, PingFang SC;
						font-weight: 600;
						font-size: 32rpx;
						color: #333333;
						font-style: normal;
					}

					.Newtitle {
						font-family: PingFangSC, PingFang SC;
						font-weight: 500;
						font-size: 24rpx;
						color: #333333;
						font-style: normal;
					}
				}
			}

			button {
				width: 154rpx;
				height: 60rpx;
				// background: linear-gradient(270deg, #3078FF 0%, #009DFE 100%);
				border-radius: 46rpx;
				margin: 0px;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				font-size: 26rpx;
			}
		}

		.BoxBottom {
			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32rpx;
				color: #333333;
				margin-top: 25rpx;
				margin-bottom: 10rpx;
				display: block;
			}

			.TimeFlex {
				display: flex;
				align-items: center;

				.TimeTitle {
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #333333;
					margin-right: 10rpx;
				}
			}

			.Boxinfo {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 25rpx;
				margin-bottom: 25rpx;

				.u-Flex {
					display: flex;
					align-items: center;

					text {
						font-family: PingFangSC, PingFang SC;
						font-weight: 500;
						font-size: 24rpx;
						color: #333333;
						margin-left: 5rpx;
					}
				}
			}

			.time {
				@include flex;
				align-items: center;

				.Timetext {
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #F1330D;
					margin-left: 5rpx;
					margin-right: 5rpx;
				}

				.time__doc {
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #F1330D !important;
				}

				&__custom {
					// margin-top: 4px;
					width: 20px;
					height: 20px;
					background-color: #ffb1b0;
					border-radius: 4px;
					/* #ifndef APP-NVUE */
					display: flex;
					/* #endif */
					justify-content: center;
					align-items: center;

					&__item {
						color: #F1330D !important;
						font-size: 12px;
						text-align: center;
					}
				}

				&__doc {
					color: $u-primary;
					padding: 0px 4px;
				}

				&__item {
					color: #606266;
					font-size: 15px;
					margin-right: 4px;
				}
			}
		}

		.checkTx {
			width: 88%;
			padding: 25rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 0px auto;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			background-color: #fff;
			border-radius: 20rpx;

			.checkTx_title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 28rpx;
				color: #333333;
			}

			.checkTx_view {
				display: flex;
				align-items: center;

				.checkTx_Text {
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #888888;
					margin-right: 10rpx;
				}
			}
		}
	}
</style>